import 'reflect-metadata'

type MyPropDecorator = (targetClassPrototype: any, propertyKey: string | symbol) => void

export function Singleton(singleton: boolean): MyPropDecorator {
    return (targetClassPrototype, propertyKey) => {
        // PropServiceClass，如：UserServiceInter
        let PropServiceClass = Reflect.getMetadata("design:type", targetClassPrototype, propertyKey);
        // ServiceImplClass，如：UserServiceImpl
        let ServiceImplClass = PropServiceClass.getImplClass();

        let ServiceImplInstanceOrClass;
        let metaSingleton = Reflect.getMetadata("singleton", targetClassPrototype, propertyKey);
        if (singleton) {
            if (!metaSingleton) { //第一次进入
                Reflect.defineMetadata("singleton", singleton, targetClassPrototype, propertyKey);
                ServiceImplInstanceOrClass = ServiceImplClass.getInstance();
            } else { // 第二次或以上次重复进来执行
                console.log("单件模式创建,使用了上一次的对象");
            }
        } else {
            ServiceImplInstanceOrClass = ServiceImplClass;
        }
        //保存对象或类
        Reflect.defineMetadata("ServiceImplInstanceOrClass", ServiceImplInstanceOrClass, targetClassPrototype, propertyKey);
    }
}
